package com.jsh.service.basic;

import com.jsh.base.BaseService;
import com.jsh.base.Log;
import com.jsh.dao.basic.BomIDAO;
import com.jsh.dao.basic.UserBusinessIDAO;
import com.jsh.model.po.Bom;
import com.jsh.util.*;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.write.*;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import java.io.*;
import java.lang.Boolean;
import java.util.*;
 
public class BomService extends BaseService<Bom> implements BomIService
{
	@SuppressWarnings("unused")
	private BomIDAO BomDao;
	@SuppressWarnings("unused")
	private UserBusinessIDAO userBusinessDao;

	/**
	 * 设置映射基类
	 * @return
	 */
	@Override
	protected Class<Bom> getEntityClass()
	{
		return Bom.class;
	}
	
	public void setBomDao(BomIDAO BomDao)
	{
		this.BomDao = BomDao;
	}

	public void setUserBusinessDao(UserBusinessIDAO userBusinessDao) {
		this.userBusinessDao = userBusinessDao;
	}

	public void batchSetEnable(Boolean enable,String BomIDs){
		BomDao.batchSetEnable(enable, BomIDs);
	}

	/**
	 * 初始化加载所有系统基础数据
	 */
	@SuppressWarnings({"rawtypes"})
	private static Map<String,List> mapData = new HashMap<String, List>();

	/**
	 * 错误的表格数据
	 */
	private static List<Bom> wrongData = new ArrayList<Bom>();
	/**
	 * 导出Excel表格
	 */
	@Override
	public InputStream exmportExcel(String isAllPage, PageUtil<Bom> pageUtil)throws JshException
	{
		try
		{
			
			//将OutputStream转化为InputStream
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			putDataOnOutputStream(out, pageUtil.getPageList());
			return new ByteArrayInputStream(out.toByteArray());
		}
		catch (Exception e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>>>>>>导出信息为excel表格异常", e);
			throw new JshException("导出信息为excel表格异常",e);
		}
	}

	/**
	 * 生成excel表格
	 * @param os
	 */
	@SuppressWarnings("deprecation")
	private void putDataOnOutputStream(OutputStream os, List<Bom> dataList) {
		WritableWorkbook workbook = null;
		try {
			workbook = Workbook.createWorkbook(os);
			WritableSheet sheet = workbook.createSheet("信息报表", 0);
			//增加列头
			String[] colunmName = {"Item","Qty.","Ref.Designator","Complete Part No. or Doc.No","Description","Pakage type or Doc Type","Value or Rev.","Voltage","Tolerances","Special Comments","RoHS","Temperature Range","Manufacturer","Supplier","Supplier Part No.","Second source Manufacturer","Second source Part no.","DR Part Number"};
			for(int i = 0 ;i < colunmName.length;i ++) {
				sheet.setColumnView(i, 10);
				sheet.addCell(new Label(i, 0, colunmName[i]));
			}
			if (null != dataList && dataList.size() > 0) {
				int i = 1;
				for (Bom bom: dataList){
					int j = 0;
					String str="";
					Map<Integer, String> cellInfo = bom.getCellInfo();
					sheet.addCell(new Label(j++,i, (String) (bom.getItem()==null?"":bom.getItem().toString())));
					//sheet.addCell(getLabelInfo(cellInfo, j++,i, bom.getQty()==null?"":bom.getQty().toString(),bom));
					sheet.addCell(new Label(j++,i, (String) (bom.getQty()==null?"":bom.getQty().toString())));
					sheet.addCell(new Label(j++,i, bom.getRef_designator()==null?"":bom.getRef_designator()));
					sheet.addCell(new Label(j++,i, bom.getComplete_part()==null?"":bom.getComplete_part()));
					sheet.addCell(new Label(j++,i, bom.getDescription()==null?"":bom.getDescription()));
					sheet.addCell(new Label(j++,i, bom.getPakage_type_or_doc_type()==null?"":bom.getPakage_type_or_doc_type()));
					sheet.addCell(new Label(j++,i, bom.getValue_or_rev()==null?"":bom.getValue_or_rev()));
					sheet.addCell(new Label(j++,i, bom.getVoltage()==null?"":bom.getVoltage()));
					sheet.addCell(new Label(j++,i, bom.getTolerances()==null?"":bom.getTolerances()));
					sheet.addCell(new Label(j++,i, bom.getSpecial_comments()==null?"":bom.getSpecial_comments()));
					sheet.addCell(new Label(j++,i, bom.getRohs()==null?"":bom.getRohs()));
					sheet.addCell(new Label(j++,i, bom.getTemperature_range()==null?"":bom.getTemperature_range()));
					sheet.addCell(new Label(j++,i, bom.getManufacturer()==null?"":bom.getManufacturer()));
					sheet.addCell(new Label(j++,i, bom.getSupplier()==null?"":bom.getSupplier()));
					sheet.addCell(new Label(j++,i, bom.getSupplier_part_no()==null?"":bom.getSupplier_part_no()));
					sheet.addCell(new Label(j++,i, bom.getSecond_source_manufacturer()==null?"":bom.getSecond_source_manufacturer()));
					sheet.addCell(new Label(j++,i, bom.getSecond_source_part_no()==null?"":bom.getSecond_source_part_no()));
					sheet.addCell(new Label(j++,i, bom.getDr_rart_number()==null?"":bom.getDr_rart_number()));
					sheet.addCell(new Label(j++,i, bom.getEnabled() != null?"启用":"禁用"));
					i++;
				}
			}
			workbook.write();
			workbook.close();
		}
		catch (Exception e) {
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>>>>>>导出信息为excel表格异常", e);
		}
	}

	/**
	 * 根据错误信息进行提示--excel表格背景设置为红色，表示导入信息有误
	 * @param cellInfo
	 * @param cellNum
	 * @param columnNum
	 * @param value
	 * @return
	 */
	private Label getLabelInfo(Map<Integer,String> cellInfo,int cellNum,int columnNum,String value,Bom bom)
	{
		Label label = null;

		//设置背景颜色
		WritableCellFormat cellFormat = new WritableCellFormat();
		try
		{
			cellFormat.setBackground(Colour.RED);
		}
		catch (WriteException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>>>>设置单元格背景颜色错误", e);
		}
		return label;
	}

	@Override
	public InputStream importExcel(File assetFile) throws JshException {
		//全局变量--每次调用前需要清空数据
		mapData.clear();
		//2、解析文件成资产数据
		parseFile(assetFile);

		if(null != wrongData && wrongData.size()>0) {
			//将OutputStream转化为InputStream
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			putDataOnOutputStream(out,wrongData);
			return new ByteArrayInputStream(out.toByteArray());
		}
		else{
			return null;
		}
	}

	/**
	 * 解析excel表格
	 * @param assetFile
	 */
	@SuppressWarnings("unchecked")
	private void parseFile(File assetFile) {
		//每次调用前清空
		wrongData.clear();
		int totalRow = 0;
		try {
			//创建对Excel工作簿文件的引用
			HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(assetFile));
			//创建对工作表的引用,获取第一个工作表的内容
			HSSFSheet sheet = workbook.getSheetAt(0);
			/**
			 * =====================================
			 * 1、此处要增加文件的验证，如果不是资产文件需要进行特殊的处理,13列
			 * 2、文件内容为空处理
			 * 3、如果是修改过的文件内容
			 */
			Iterator<Row> itsheet = sheet.rowIterator();
			while(itsheet.hasNext()) { 
				//获取当前行数据
				Row row = itsheet.next();
				//获取一行有多少单元格
//                System.out.println(row.getLastCellNum());

				//excel表格第几行数据 从1开始 0 是表头
				int rowNum = row.getRowNum();
				/**
				 * 表头跳过不读
				 */
				if(BomConstants.BusinessForExcel.EXCEL_TABLE_HEAD ==  rowNum)
					continue;

				//开始处理excel表格内容 --每行数据读取,同时统计总共行数
				totalRow ++;

				//获取excel表格的每格数据内容
				Iterator<Cell> it = row.cellIterator();
				//资产子类型--添加了一些excel表格数据
				Bom bom = new Bom();
				//保存每个单元格错误类型
				Map<Integer, String> cellType = new HashMap<Integer,String>();
				//设置列号
				bom.setRowLineNum(rowNum);

				Cell cell = null;
				//判断列号--从零开始
				int cellIndex = 0;
				while(it.hasNext()) {
					//获取每个单元格对象
					cell = it.next();
					//获取列号
					cellIndex = cell.getColumnIndex();
					
					//设置此单元格为字符串类型
					cell.setCellType(Cell.CELL_TYPE_STRING);

					Log.infoFileSync("==================excel表格中第" + totalRow + "行的第 " + cellIndex + "列的值为" + cell.getStringCellValue());					switch(cellIndex) {
					case BomConstants.BusinessForExcel.EXCEL_ITEM:
						int item = Integer.parseInt(cell.getStringCellValue());
						bom.setItem(item);
						break;
					case BomConstants.BusinessForExcel.EXCEL_QTY :
						int qty = Integer.parseInt(cell.getStringCellValue());
						bom.setQty(qty);
						break;
					case BomConstants.BusinessForExcel.EXCEL_REF_DESRGNATOR:
						String ref_designator = cell.getStringCellValue();

						bom.setRef_designator(ref_designator);
						break;
					case BomConstants.BusinessForExcel.EXCEL_COMPLETE_PART :
						String complete_part = cell.getStringCellValue();
						bom.setComplete_part(complete_part);
						break;
					case BomConstants.BusinessForExcel.EXCEL_DESCRIPTION :
						String description = cell.getStringCellValue();
						bom.setDescription(description);
						break;
					case BomConstants.BusinessForExcel.EXCEL_PAKAGE_TYPE_OR_DOC_TYPE :
						String pakage_type_or_doc_type = cell.getStringCellValue();
						bom.setDescription(pakage_type_or_doc_type);
						break;
					case BomConstants.BusinessForExcel.EXCEL_VALUE_OR_REV :
						String value_or_rev = cell.getStringCellValue();
						bom.setValue_or_rev(value_or_rev);
						break;
					case BomConstants.BusinessForExcel.EXCEL_VOLTAGE :
						String voltage = cell.getStringCellValue();
						bom.setVoltage(voltage);
						break;
					case BomConstants.BusinessForExcel.EXCEL_TOLERANCES :
						String tolerances = cell.getStringCellValue();
						bom.setTolerances(tolerances);
						break;
					case BomConstants.BusinessForExcel.EXCEL_SRECIAL_COMMENTS :
						String special_comments = cell.getStringCellValue();
						bom.setSpecial_comments(special_comments);
						break;
					case BomConstants.BusinessForExcel.EXCEL_ROHS :
						String rohs = cell.getStringCellValue();
						bom.setRohs(rohs);
						break;
					case BomConstants.BusinessForExcel.EXCEL_TEMPERATURE_RANGE :
						String temperature_range = cell.getStringCellValue();
						bom.setTemperature_range(temperature_range);
						break;
					case BomConstants.BusinessForExcel.EXCEL_MANUFACTURER :
						String manufacturer = cell.getStringCellValue();
						bom.setManufacturer(manufacturer);
						break;
					case BomConstants.BusinessForExcel.EXCEL_SUPPLIER :
						String supplier = cell.getStringCellValue();
						bom.setSupplier(supplier);
						break;
					case BomConstants.BusinessForExcel.EXCEL_SUPPLIER_PART_NO :
						String supplier_part_no = cell.getStringCellValue();
						bom.setSupplier_part_no(supplier_part_no);
						break;
					case BomConstants.BusinessForExcel.EXCEL_SECOND_SOURCE_MANUFACTURER :
						String second_source_manufacturer = cell.getStringCellValue();
						bom.setSecond_source_manufacturer(second_source_manufacturer);
						break;
					case BomConstants.BusinessForExcel.EXCEL_SECOND_SOURCE_PART_NO :
						String second_source_part_no = cell.getStringCellValue();
						bom.setSecond_source_part_no(second_source_part_no);
						break;
					case BomConstants.BusinessForExcel.EXCEL_DR_RART_NUMBER :
						String dr_rart_number = cell.getStringCellValue();
						bom.setDr_rart_number(dr_rart_number);
						break;
				}
			
				}
				bom.setCellInfo(cellType);
	
				Log.infoFileSync(totalRow + "行总共有" + cellIndex + "列");

				//判断完成后增加数据
				if((null!=cellType && cellType.size() >0) || bom.getItem() == null) {
					wrongData.add(bom);
				}
				else {
					bom.setEnabled(true);
					bom.setIsystem((short)1);
					System.out.println(bom);
					BomDao.save(bom);
				}
			}
		}
		catch (FileNotFoundException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>读取excel文件异常:找不到指定文件！",e);
		}
		catch (IOException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>读取excel文件异常，请确认文件格式是否正确 ！",e);
		}
		Log.infoFileSync("===================excel表格总共有 " + totalRow + " 条记录!");
	}


}
